package com.iemes.service.impl.workcenter_model;

import java.util.List;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.iemes.entity.ResFormMap;
import com.iemes.entity.SiteFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.site.SiteMapper;
import com.iemes.service.workcenter_model.SiteService;
import com.iemes.util.ListUtils;
import com.iemes.util.UUIDUtils;

@Service
public class SiteServiceImpl implements SiteService {
	
	@Inject
	private SiteMapper siteMapper;
	
	private Logger log = Logger.getLogger(this.getClass());

	@Override
	@Transactional
	public void saveSite(SiteFormMap siteFormMap) throws BusinessException {
		try {
			String id = siteFormMap.getStr("id");
            String site = siteFormMap.getStr("site");
			
			if(StringUtils.isEmpty(site)) {
				throw new BusinessException("站点编号不能为空，请输入！");
			}			
			
			SiteFormMap siteFormMap2 = new SiteFormMap();
			siteFormMap2.put("site", site);
			List<SiteFormMap> listSiteFormMap = siteMapper.findByNames(siteFormMap2);

			//如果编号存在，就执行更新，不存在就执行新增
			if (ListUtils.isNotNull(listSiteFormMap)) {
				//更新 
				SiteFormMap siteFormMap3 = new SiteFormMap();
				siteFormMap3 = listSiteFormMap.get(0);
				id = siteFormMap3.getStr("id");
				siteFormMap.set("id", id);
				
				siteMapper.editEntity(siteFormMap);
			}else {
				//新增
				siteFormMap.put("id", UUIDUtils.getUUID());
				siteMapper.addEntity(siteFormMap);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("站点保存失败！" + e.getMessage());
		}
	}

	@Override
	@Transactional
	public void delSite(String id) throws BusinessException {
		try {
			siteMapper.deleteByAttribute("id", id, SiteFormMap.class);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("用户删除失败！"+e.getMessage());
		}
	}

}
